package com.shop.web.response;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.shop.web.context.WebContext;

import java.io.Serializable;

public class BaseResponse<T> implements Serializable {

    public static final BaseResponse SUCCESS = new BaseResponse(RetEnum.SUCCESS);
    public static final BaseResponse FAIL = new BaseResponse(RetEnum.FAIL);
    public static final BaseResponse SYSTEM_EXCEPTION = new BaseResponse(RetEnum.SYSTEM_EXCEPTION);
    public static final BaseResponse ERROR_PARAM = new BaseResponse(RetEnum.ERROR_PARAM);
    public static final BaseResponse ILLEGAL_REQUEST = new BaseResponse(RetEnum.ILLEGAL_REQUEST);
    public static final BaseResponse NEED_LOGIN = new BaseResponse(RetEnum.NEED_LOGIN);
    public static final BaseResponse ALREADY_EXECUTE = new BaseResponse(RetEnum.ALREADY_EXECUTE);
    public static final BaseResponse CHECK_SIGN_IS_FAIL = new BaseResponse(RetEnum.CHECK_SIGN_IS_FAIL);


    private String accessToken;
    private String code;
    private String msg;
    private T content;
    private long timestamp;

    public BaseResponse() {
        this(RetEnum.SUCCESS);
    }

    public BaseResponse(Ret ret) {
        this(ret, null);
    }

    public BaseResponse(T content) {
        this(RetEnum.SUCCESS, content);
    }

    public BaseResponse(Ret ret, T content) {
        this(ret.getCode(), ret.getMsg(), content);
    }

    public BaseResponse(String code, String msg, T content) {
        this.accessToken = WebContext.getAccessToken();
        this.code = code;
        this.msg = msg;
        this.content = content;
        this.timestamp = System.currentTimeMillis();
    }

    @JSONField(ordinal = 10)
    public String getAccessToken() {
        return accessToken;
    }

    @JSONField(ordinal = 20)
    public String getCode() {
        return code;
    }

    @JSONField(ordinal = 30)
    public String getMsg() {
        return msg;
    }

    public BaseResponse setMsg(String msg) {
        this.msg = msg;
        return this;
    }

    @JSONField(ordinal = 40)
    public T getContent() {
        return content;
    }

    @JSONField(ordinal = 50)
    public long getTimestamp() {
        return timestamp;
    }

    public BaseResponse setContent(T content) {
        this.content = content;
        return this;
    }

    public boolean success() {
        return RetEnum.SUCCESS.getCode().equals(this.code);
    }

    public static BaseResponse fail(String msg) {
        return new BaseResponse(RetEnum.FAIL).setMsg(msg);
    }

    public static BaseResponse success(String msg) {
        return new BaseResponse(RetEnum.SUCCESS).setMsg(msg);
    }

    public String toJSONString() {
        return JSON.toJSONString(this);
    }



    public String toString() {
        return JSON.toJSONString("");
    }
}
